package com.fisher.IdempotentDemo.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.fisher.IdempotentDemo.constant.TokenConstant;
import com.fisher.IdempotentDemo.exception.ServiceException;
import com.fisher.IdempotentDemo.service.CacheService;
import com.fisher.IdempotentDemo.service.TokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;

/**
 * @author ：fisher wu
 * @date ：Created in 2021/11/23 9:25 上午
 * @description：token服务接口实现类
 */
@Service
public class TokenServiceImpl implements TokenService {

    @Autowired
    private CacheService cacheService;
    /**
     * 创建token
     *
     * @return token串
     */
    @Override
    public String createToken() {
        String uuid = IdUtil.randomUUID();
        StringBuilder token = new StringBuilder();
        try{
            String replace = uuid.replace("-", "");
            token.append(TokenConstant.REDIS_PREFIX).append(replace);
            cacheService.setEx(token.toString(), token.toString(), 10000L);
            boolean notEmpty = StrUtil.isNotEmpty(token.toString());
            if (notEmpty) {
                return token.toString();
            }
        }catch (Exception exception){
            exception.printStackTrace();;
        }
        return null;
    }

    /**
     * 从请求头Header中获取token值进行校验，通过抛出的Exception
     * 来获取具体的报错信息返回给前端
     *
     * @param request http请求对象
     * @return 校验结果
     */
    @Override
    public boolean checkToken(HttpServletRequest request) throws Exception {
        String token = request.getHeader(TokenConstant.TOKEN_NAME);
        if (StrUtil.isBlank(token)) {
            // header中不存在token
            token = request.getParameter(TokenConstant.TOKEN_NAME);
            if (StrUtil.isBlank(token)) {
                // parameter中也不存在token
                throw new ServiceException("TOKEN不存在");
            }
        }

        if (!cacheService.exists(token)) {
            // 缓存中不存在token 重复请求
            throw new ServiceException("请勿重复提交该请求");
        }

        boolean remove = cacheService.remove(token);
        if (!remove) {
            // redis删除token失败，校验失败
            throw new ServiceException("删除失败，请重试");
        }
        return true;
    }
}
